﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Cit.CDE.Net.Service.ModuleFactory;
using Cit.CDE.Net.Module;
using System.Collections.Generic;
using Cit.CDE.Net.Module.Commons;
using cde.SystemCommon;
using Cit.CDE.Net.Service;
using System.Text;

using Module;
using Telerik.WebControls;
using System.IO;


/// <summary>
/// Copyright (C)   jinggubang
/// FileName:        LoreEdit.aspx.cs           
/// Author :         wangbc
/// CDT:             2012-02-01           
/// Version:         1.0.0.0                
/// Depiction:       资料新增    
/// </summary>
public partial class main_admin_LoreEdit : UserControl.CommonPage
{
    /// <summary>
    /// 资料EM
    /// </summary>
    private CDEEntityManager em;
    /// <summary>
    /// 资料Entity
    /// </summary>
    private CDEEntity m_entity;
    /// <summary>
    /// 资料Entity名字
    /// </summary>    
    private const string EM_FULL_NAME = WEBConstants.EM_LORE_MANAGE;

    /// <summary>
    /// 操作员ID
    /// </summary>
    private string opId;

    /// <summary>
    /// 类型ID
    /// </summary>
    public string type_id;

    /// <summary>
    /// 文件ID
    /// </summary>
    public string SOURCE_ID = string.Empty;

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //当前登陆人信息
        LoginOprator op = (LoginOprator)Session[Cit.CDE.Net.Module.Commons.CDEConstants.SESSION_LOIN_OPRATOR];
        opId = op.SysID;

        //资料ID
        string chkID = (string)Request.QueryString.Get("chkID");
        //只显示设定类型数据 type_id:1-产品部,2-市场部,3-培训部,19-网上申请     
        type_id = (string)Request.QueryString.Get("type_id"); 

        em = CDEEMFactory.getEMByFullName(EM_FULL_NAME);
        if (!Page.IsPostBack)
        {
            //当前登陆人 数据权限处理           
            //除产品部外，其它员工只能看自己所属区域数据
            if (op.POST == "0" && type_id != "1")
            {
                this.tr_AREA_ID.Visible = false;
            }

            //根据类型ID设置默认可选类型
            if (type_id != "")
            {
                string type_code = string.Empty;
                if (type_id == "1")
                {
                    type_code = "10";
                    this.cddLoreType1.SelectedValue = type_code + "000000";
                }
                else if (type_id == "2")
                {
                    type_code = "11";
                    this.cddLoreType1.SelectedValue = type_code + "000000";
                }
                else if (type_id == "3")
                {
                    type_code = "12";
                    this.cddLoreType1.SelectedValue = type_code + "000000";
                }
                else
                {
                    type_code = "11020100";
                    this.cddLoreType1.SelectedValue = type_code.Substring(0, 2) + "000000";
                    this.cddLoreType2.SelectedValue = type_code.Substring(0, 4) + "0000";
                    this.cddLoreType3.SelectedValue = type_code.Substring(0, 6) + "00";
                    tr_loreType.Visible = false;
                }
            }


            //ID不为空修改资料，否则新增资料
            if (chkID != "" && chkID != null)
            {
                //修改
                this.page_title.InnerText = "资料修改";
                CDESearchCriteria sc = new CDESearchCriteria(em);
                sc.addCondition("ID", chkID);
                List<CDEEntity> listEntity = CDEService.LoadEntities(em, sc);
                //资料ID是否存在
                if (listEntity.Count > 0)
                {
                    m_entity = listEntity[0];
                    m_entity.Operation = CDEDataOperation.UPDATE;

                    //设定类型
                    string add_code = Util.objectToString(m_entity.get("LORE_TYPE__TYPE_CODE"));
                    if (add_code!="")
                    {                        
                        this.cddLoreType1.SelectedValue = add_code.Substring(0, 2) + "000000";
                        this.cddLoreType2.SelectedValue = add_code.Substring(0, 4) + "0000";
                        this.cddLoreType3.SelectedValue = add_code.Substring(0, 6) + "00";
                        this.cddLoreType4.SelectedValue = add_code;
                    }

                    //网上申请发通知
                    if (add_code == "11020100")
                    {
                        //可以发送通知
                        SOURCE_ID = m_entity.Id;
                        btnChooseUsers.Visible = true;
                    }
                }
                else
                {
                    m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                    m_entity.Operation = CDEDataOperation.INSERT;
                } 
            }
            else
            {
                //新增
                this.page_title.InnerText = "资料新增";
                m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                m_entity.Operation = CDEDataOperation.INSERT;
                
            }

            Session["MENTITY"] = m_entity;
            //资料信息设值到页面
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);


            //文件名画面显示
            string fileName = Util.objectToString(m_entity.get("FILE_PATH"));
            if (fileName != "")
            {
                this.showFile.Style.Value = "display:block";
                this.file_name.InnerHtml = fileName;
                this.upFile.Style.Value = "display:none";
            }
        }
        else
        {
            m_entity = (CDEEntity)Session["MENTITY"];
            //页面信息放入资料Entity
            this.setEntityFromRequest(m_entity, Request.Params);
        }
    }
    /// <summary>
    /// 确定按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void queding_Click(object sender, EventArgs e)
    {
        //当前时间
        string Now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");
        if (m_entity.Operation == CDEDataOperation.INSERT)
        {
            m_entity.set("INSERT_USER", opId);
            m_entity.set("INSERT_DATE", Now);
        }
        else
        {
            m_entity.set("UPDATE_USER", opId);
            m_entity.set("UPDATE_DATE", Now);
        }
        //当前登陆人信息
        LoginOprator op = (LoginOprator)Session[Cit.CDE.Net.Module.Commons.CDEConstants.SESSION_LOIN_OPRATOR];
        //除产品部外，其它员工只能看自己所属区域数据
        if (op.POST == "0" && type_id != "1")
        {
            if (op.AREA_ID != "")
            {
                m_entity.set("AREA_ID", op.AREA_ID);
            }
        }

        List<CDEEntity> listEntity = new List<CDEEntity>();
        listEntity.Add(m_entity);
        bool isSaveError = false;
        string chkID = (string)Request.QueryString.Get("chkID");
        
        //类型代码
        string type_code = "";
        if (type_id == "19")
        {
            type_code = "11020100";
        }
        else
        {            
            //一级分类
            string typecode1 = cutCodeFromCodeAndName(this.cddLoreType1.SelectedValue.ToString());
            //二级分类
            string typecode2 = cutCodeFromCodeAndName(this.cddLoreType2.SelectedValue.ToString());
            //三级分类
            string typecode3 = cutCodeFromCodeAndName(this.cddLoreType3.SelectedValue.ToString());
            //四级分类
            string typecode4 = cutCodeFromCodeAndName(this.cddLoreType4.SelectedValue.ToString());


            if (typecode4 != "")
            {
                type_code = typecode4;
            }
            else if (typecode3 != "")
            {
                type_code = typecode3;
            }
            else if (typecode2 != "")
            {
                type_code = typecode2;
            }
            else if (typecode1 != "")
            {
                type_code = typecode1;
            }
        }

        //类型CODE
        m_entity.set("LORE_TYPE", null);
        m_entity.set("LORE_TYPE__TYPE_NAME", null);
        m_entity.set("LORE_TYPE__TYPE_CODE", type_code); 

        CDEService.UpdateEntities(em, listEntity);

        if (listEntity[0].Result == CDEDataOperationResult.ERROR)
        {
            isSaveError = true;
        }
        else
        {
            //上传的文件重合名为课件ID
            // string Path = Server.MapPath(@"~/Uploads");
            string Path = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["Lore"]);

            string oldFileName = Path + m_entity.get("FILE_PATH");
            string newFileName = Path + m_entity.get("LORE_ID");

            if (File.Exists(oldFileName))
            {
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }
                File.Move(oldFileName, newFileName);
            }

            if (type_code == "11020100")
            {
                //可以发送通知
                SOURCE_ID = m_entity.Id;
                btnChooseUsers.Visible = true;
            }

            isSaveError = false;
        }
  

        //成功返回列表，失败提示错误信息
        if (isSaveError)
        {
            showMessageErrAndOk(Resources.ResourceErrMsg.SAVE_ERR);
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);
        }
        else
        {
         
            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            //sbr.AppendFormat("window.location='../admin/LoreList.aspx?EM=" + EM_FULL_NAME + "&sel_menu_id=" + Sel_MenuNode.Attributes["id"].Value + "&IsBackSc=1&type_id="+type_id+"';{0}", Environment.NewLine);

            if (type_code == "11020100")
            {
                //可以发送通知
                sbr.AppendFormat(" openChooseUsers('1');");
            }
            else {
                sbr.AppendFormat("alert(\"");
                sbr.AppendFormat(Resources.Resource.RESULT_OK);
                sbr.AppendFormat("\");");

            }
            sbr.AppendFormat("</script>");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
        }

    }

    /// <summary>
    /// 把联动下拉单中的选择值处理一下只剩下code
    /// </summary>
    /// <param name="codeAndName">处理前</param>
    /// <returns>处理后</returns>
    protected string cutCodeFromCodeAndName(string codeAndName)
    {
        string result = "";
        int index = codeAndName.IndexOf(":");
        if (index > 0)
        {
            result = codeAndName.Substring(0, index);
        }
        return result;
    }

    /// <summary>
    /// 返回按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        if (Sel_MenuNode == null)
            return;
        StringBuilder url = new StringBuilder();
        url.Append("../admin/LoreList.aspx?EM=");
        url.Append(EM_FULL_NAME);
        url.Append("&sel_menu_id=");
        url.Append(Sel_MenuNode.Attributes["id"].Value);
        url.Append("&IsBackSc=1");
        url.AppendFormat("&type_id={0}", type_id);
        Response.Redirect(url.ToString());

    }


    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
            // string Path = Server.MapPath(@"~/Uploads");
            string Path = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["Lore"]);

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }

            //课件名称默认为文件名
            string fileName = file.GetName().ToString();
            this.txt_Lore_TITLE.Text = fileName;

            //组合路径，file.GetName()取得文件名
            Path = Path + fileName;

            //保存
            file.SaveAs(Path, true);

            //设置文件信息
            m_entity.set("FILE_SIZE", file.ContentLength);
            m_entity.set("FILE_PATH", file.GetName());
            m_entity.set("FILE_TYPE", file.GetExtension().ToLower());


            this.showFile.Style.Value = "display:block";
            this.file_name.InnerHtml = file.GetName().ToString();
            this.upFile.Style.Value = "display:none";
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDelFile_Click(object sender, EventArgs e)
    {

        this.showFile.Style.Value = "display:none";
        this.file_name.InnerHtml = "";
        this.upFile.Style.Value = "display:block";
    }
}
